//
//  QCAbountViewController+XLBIN.swift
//  爱汽车
//
//  Created by xinglian on 2024/4/9.
//

import UIKit
import TCCKit
//MARK: - 客户MCU的OTA - START
extension QCAboutViewController{
    
    var  OTA_bytes: [UInt8] {
        get{
            return bytes
        }
        set{
            let ack = bytes[7]
            let data = [UInt8](bytes[AI_index..<bytes.count])
            switch ack{
                //MARK: - 客户MCU OTA - START
            case UInt8(AIQC.boot.ack):
                if match {return}
                MyPrint("==================  接受 C2")
                boot = Int(data[0]) == 1
                prepareXLBin(3)
                //prepareXLBin(boot ? 3 : 2)
                match = true
            case UInt8(AIQC.codeMatch.ack):
                sendXLBin()
                MyPrint("==================  接受 C0")
            case UInt8(AIQC.OTA.ack):
                bin_index += 1
                MyPrint("==================  接受 C4  第\(bin_index)个包")
                sendXLBin()
            case UInt8(AIQC.CRC.ack):
                CCHud.start("升级成功", stopTime: 1.5)
                btnState(text: "已是最新", index:btn_select_index)
            case UInt8(AIQC.bootExit.ack):
                MyPrint("==================  接受 C6  \(UInt8(bytes[8]) == 0 ? "正常退出" : "超时退出")")
                //MARK: - 客户MCU OTA - END
            default:
                break
            }
        }
    }
    
    /// 拆分包
    /// - Parameters:
    ///   - data: 需要拆分的数据
    ///   - packetSize: 每个小包的长度，512个字节
    func XLBIN_OTA(_ packetSize:Int = 512){
        guard var data = current_OTA_Model.data as? NSData else{return}
        ///根据客户文档，这里要去除帧头等其他信息，只保留纯数据内容
        data = data.subdata(with: NSRange(location: 32, length: data.count-32-2)) as NSData
        boot = false
        match = false
        bin_index = 0
        bin_array.removeAll()
        var offset = 0
        
        while offset < data.length {
            // 计算剩余字节数和实际分组大小
            let remainingBytes = data.length - offset
            let size = min(packetSize, remainingBytes)
            
            // 从原始数据中提取分组
            let range = NSRange(location: offset, length: size)
            let packetData = data.subdata(with: range)
            handle(NSMutableData(data: packetData), offset, size, packetSize)
            
            // 更新偏移量
            offset += size
        }
        prepareXLBin()
        
        /// 加工每个分包
        /// - Parameters:
        ///   - data: 分包数据
        ///   - offset: 分包的偏移量
        ///   - currentSize: 分包数据大小
        ///   - packetSize: 分包要求的大小 默认=512
        func handle(_ data:NSMutableData, _ offset:Int, _ currentSize:Int, _ packetSize:Int=512){
            let index = offset / packetSize
            let index_hex = "\(index)".toHex2().fixString(4, "0")///512分包序号
            let length_hex = "\(currentSize)".toHex2().fixString(4, "0")///512分包数据长度
            
            //特别注意： 如果分组大小不足512字节，则使用0填充
            if currentSize < packetSize {
                let paddingSize = packetSize - currentSize
                let paddingData = Data(repeating: 0, count: paddingSize)
                data.append(paddingData)
                var s = [UInt8](data).map{String(format: "%02X ", $0)}.joined()
                MyPrint("最后一个包 === \(s)")
            }
            ///分包转换成hex字符串
            var data_hex = [UInt8](data).map{String(format: "%02X", $0)}.joined()
            data_hex = index_hex+length_hex+data_hex///再拼接
            
            ///数据校验
            var sub_result = BLEData.appSetDataToPer(AIQC.OTA.cmd, data_hex).hex
            ///按照智联硬件封装帧头等信息
            let sub_result_l = "\(sub_result.count / 2 + 2)".toHex().fix(8, "0")
            let header = String(format:"880000%@00%@", sub_result_l, "0120")
            sub_result = header+sub_result
            bin_array.append(sub_result.hexadecimal() ?? Data())
        }
    }
    
    /// 预备写数据
    /// - Parameter step: step = 1  模块复位
    /// - Parameter step: step = 2  进入BOOT
    /// - Parameter step: step = 3  型号匹配
    func prepareXLBin(_ step:Int=1){
        switch step{
        case 1:
            CCHud.start(LS("模块复位"))
            MyPrint("==================  发送 41 ")
            BLEData.appSetDataToPer(AIQC.reset.cmd, "00").write
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {[weak self] in
                guard let self = self else{return}
                // 在主队列上异步延迟执行任务，即100毫秒后执行
                BLEData.appSetDataToPer(AIQC.reset.cmd, "00").write
                MyPrint("==================  发送 41 ")
                self.prepareXLBin(2)
            }
        case 2:
            MyPrint("==================  测试  booT=\(boot) match = \(match)")
            if match {return}
            if boot{
                // prepareXLBin(3)
                return
            }
            CCHud.start(LS("进入BOOT"))
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {[weak self] in
                guard let self = self else{return}
                // 在主队列上异步延迟执行任务，即100毫秒后执行
                BLEData.appSetDataToPer(AIQC.boot.cmd, "00").write
                MyPrint("==================  发送 42  booT=\(boot) match = \(match)")
                //self.prepareXLBin(2)
            }
        case 3:
            CCHud.start(LS("型号匹配"))
            guard let data = current_OTA_Model.data as? NSData else{return}
            let code = [UInt8](data[6..<6+16])
            let codestr = code.map{String(format: "%02X", $0)}.joined()
            BLEData.appSetDataToPer(AIQC.codeMatch.cmd, codestr).write
            MyPrint("==================  发送 匹配码  booT=\(boot) match = \(match)")
        default:
            break
        }
    }
    
    /// 发送小包时，再拆包
    func sendXLBin(){
        guard let data = current_OTA_Model.data as? NSData else{return}
        let bytes = [UInt8](data)
        if bin_index >= bin_array.count {
            // let hex = crc16(bytes)
            let hex = bytes[bytes.count-2..<bytes.count].map{String(format: "%02X", $0)}.joined()
            BLEData.appSetDataToPer(AIQC.CRC.cmd, hex).write
            boot = false
            match = false
            return
        }
        
        let per = String(format:"%d%%", Int(CGFloat(bin_index+1)/CGFloat(bin_array.count)*100))
        CCHud.start(LS("发送数据中...")+per)
        btnState(text: LS("更新")+":"+"\(per)", index: btn_select_index)
        
        guard let subData = bin_array[bin_index] as? Data else{return}
        write(subData)
        
        ///真正的开始写数据
        func write(_ data:Data, _ offset:Int=0){
            // 计算剩余字节数和实际分组大小
            let remainingBytes = data.count - offset
            let size = min(181, remainingBytes)
            // 从原始数据中提取分组
            guard let range = Range(NSRange(location: offset, length: size))else{return}
            let packetData = data.subdata(in: range)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
                BLEData.xlbin(packetData).write
                MyPrint("==================  发送报文 44")
                MyPrint("报文 =\(packetData.map{String(format:"%02X ", $0)}.joined())")
                // 更新偏移量
                let new_offset = size + offset
                if new_offset < data.count{
                    write(data,new_offset)
                }
            })
            
        }
        
    }
    
    
    /* CRC16 字节余式表 */
    private func crc16(_ data:[UInt8])-> String{
        let crcTable16 : [UInt16] = [
            0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
            0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
            0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
            0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
            0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
            0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
            0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
            0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
            0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
            0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
            0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
            0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
            0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
            0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
            0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
            0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0]
        
        var crc: UInt16 = 0x0000
        for byte in data {
            crc = (crc << 8) ^ crcTable16[Int((crc >> 8) ^ UInt16(byte) & 0xff)]
        }
        let hexString = String(format: "%04X", crc)
        return hexString
    }
}
//MARK: - 客户MCU的OTA - END
